#  begin by clearing memory
rm(list=ls())
#  Load libraries
library(cmdstanr)
library(posterior)
library(readxl)
# Set directory
setwd("/Users/mwatson/Dropbox/TVExtreme/ReplicationFiles/Stan/Returns")

# --- Run for largest returns then for smallest returns
# Specify model input
stan_dir <- "/Users/mwatson/Dropbox/TVExtreme/ReplicationFiles/Stan/Stan_Code"
application_dir = "/Users/mwatson/Dropbox/TVExtreme/ReplicationFiles/Stan/Returns"
model_str <- "GEV_Static_Model"

#  Returns Large
# application_str = "Returns_Large"
# data_str <- "Returns_Large"
#  Returns Small
application_str = "Returns_Small"
data_str <- "Returns_Small"

# Read Data From Excel File
data_file <- file.path(application_dir, paste0(data_str,".xlsx"))
ret <- read_excel(data_file,col_names = FALSE)

# Process data and get dimensions
# Convert to matrix
y <- as.matrix(ret)
#  Get dimensions of cs_data
T <- dim(y)[1]
k <- dim(y)[2]

# Parameter values
#  xi bounds
x_min <- -0.9
x_max <- 2.1

# Create list of data inputs for Stan
data_list <- list(
    T = T,
    nobs = k,
    xi_min = x_min,
    xi_max = x_max,
    y = t(y)
)

#  Inittial Values of parameters and seed value
trans_xi_level_init <- 0.0
ln_s_level_init <- -0.5
m_level_init <- 3.0


init_list_1 <- list(
    trans_xi_level = trans_xi_level_init,
    ln_s_level = ln_s_level_init,
    m_level = m_level_init
)
init_list_2 <- list(
    trans_xi_level = trans_xi_level_init + 0.1,
    ln_s_level = ln_s_level_init + 0.1,
    m_level = m_level_init + 0.1
)
init_list_3 <- list(
    trans_xi_level = trans_xi_level_init - 0.1,
    ln_s_level = ln_s_level_init - 0.1,
    m_level = m_level_init - 0.1
)
init_list_4 <- list(
    trans_xi_level = trans_xi_level_init + 0.0,
    ln_s_level = ln_s_level_init + 0.1,
    m_level = m_level_init + 0.1
)
seed_value <- 87123

# -------------------  Carry Out Analysis ------------------

#  Model file
model_file <- file.path(stan_dir, paste0(model_str, ".stan"))

# Output Files
draws_file <- file.path(application_dir, paste0("CSV/",application_str,".",model_str,".Draws."))
output_file <- file.path(application_dir, paste0("Output/",application_str,".",model_str))

# Compile model
mod <- cmdstan_model(model_file)

# # MCMC Draws model
fit <- mod$sample(
    data = data_list,
    iter_warmup = 5000,
    iter_sampling = 10000,
    init=list(
        init_list_1, # chain 1
        init_list_2, # chain 2
        init_list_3, # chain 3
        init_list_4  # chain 4
    ),
    refresh = 5000,
    chains = 4,
    parallel_chains = 4,
    seed = seed_value
) 
# fit diagnostics
sink(paste0(output_file,".diagonstics.txt"))
fit$diagnostic_summary()
# fit summary
sink(paste0(output_file,".summary.txt"))
fit$print(max_rows = 1000)
sink(file = NULL)

# # Save Draws of key parameters
# draws_arr <- fit$draws()

# tmp <- subset_draws(draws_arr, c("xi"))
# xi_draws <- merge_chains(tmp)
# write.csv(xi_draws, paste0(draws_file, "xi.csv"))
# #
# tmp <- subset_draws(draws_arr, c("sigma"))
# sigma_draws <- merge_chains(tmp)
# write.csv(sigma_draws, paste0(draws_file, "sigma.csv"))
# #
# tmp <- subset_draws(draws_arr, c("mu"))
# mu_draws <- merge_chains(tmp)
# write.csv(mu_draws, paste0(draws_file, "mu.csv"))




